package com.lw.sbdemo2.common.config;

import com.lw.sbdemo2.common.constant.WechatConstants;
import com.lw.sbdemo2.common.utils.ValidUtil;
import com.lw.sbdemo2.common.web.json.BodyReaderRequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>标题: 自定义过滤器</p>
 * <p>描述: @Order中的value越小，优先级越高。</p>
 * <p>版权: Copyright (c) 2018</p>
 * <p>公司: 智业软件</p>
 *
 * @author LinWang
 * @date 2018-05-09 16:43
 */
@Slf4j
public class CustomFilter implements Filter {

    private FilterConfig config;

    /**
     * 利用正则匹配不进行过滤的路径
     */
    private static List<Pattern> patterns = new ArrayList<>();
    private static Pattern FAVICON_PATTERN = Pattern.compile("^/favicon.ico$");
    private static Pattern LOGIN_PATTERN = Pattern.compile("^/.*login.html$");

    /**
     * 后台管理界面
     */
    private static Pattern MANAGE_PATTERN = Pattern.compile("^/.*manage.html$");

    @Override
    public void init(FilterConfig config) throws ServletException {
        if (log.isInfoEnabled()) {
            log.info("CustomFilter初始化......");
        }
        this.config = config;
        patterns.add(FAVICON_PATTERN);
        patterns.add(LOGIN_PATTERN);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        // 获取配置参数
        String baseUrl = config.getInitParameter("baseUrl");

        ServletRequest requestWrapper = null;
        if (request instanceof HttpServletRequest) {

            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            String url = httpServletRequest.getRequestURI();

            if (isExclude(url)) {
                chain.doFilter(request, response);
                return;
            } else {
                if (log.isInfoEnabled()) {
                    log.info("【CustomFilter】ContentType：{}，RequestURI：{}, Method：{}",
                            httpServletRequest.getContentType(), url, httpServletRequest.getMethod());
                }

                //只过滤管理界面的地址
                HttpSession session = httpServletRequest.getSession();
                String userId = (String) session.getAttribute("userId");
                if (MANAGE_PATTERN.matcher(url).matches() && ValidUtil.isEmptyOrNull(userId)) {
                    httpServletResponse.sendRedirect(baseUrl + "login.html");
                    return;
                }

                //&& (httpServletRequest.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE)
                /*
                 * POST 并且是 JSON格式才修改，目前是给@RequestJSON注解处理用的
                 */
                if (WechatConstants.HTTP_METHOD_POST.equals(httpServletRequest.getMethod().toUpperCase())
                        && MediaType.APPLICATION_JSON_VALUE.equalsIgnoreCase(httpServletRequest.getContentType())) {
                    requestWrapper = new BodyReaderRequestWrapper((HttpServletRequest) request);
                }
            }
        }

        if (requestWrapper == null) {
            chain.doFilter(request, response);
        } else {
            chain.doFilter(requestWrapper, response);
        }
    }

    @Override
    public void destroy() {
        if (log.isInfoEnabled()) {
            log.info("CustomFilter过滤器销毁......");
        }
    }

    /**
     * 是否需要排除
     */
    private boolean isExclude(String url) {
        for (Pattern pattern : patterns) {
            Matcher matcher = pattern.matcher(url);
            if (matcher.matches()) {
                return true;
            }
        }
        return false;
    }
}
